package com.jzt.gateway.filter;

import com.jzt.gateway.config.AuthConfig;
import com.jzt.gateway.config.ServersConfig;
import com.jzt.gateway.utils.UrlPathUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.cloud.gateway.route.Route;
import org.springframework.cloud.gateway.support.ServerWebExchangeUtils;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.List;

/**
 * 作者：lizw <br/>
 * 创建时间：2020/07/03 14:24 <br/>
 */
@Component
@Slf4j
public class GlobalRedirectFilter implements GlobalFilter, Ordered {
    private static final int Order = Integer.MAX_VALUE;

    @Autowired
    private ServersConfig serversConfig;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 当前Route
        final Route route = exchange.getAttribute(ServerWebExchangeUtils.GATEWAY_ROUTE_ATTR);
        if (route == null || StringUtils.isBlank(route.getId())) {
            return chain.filter(exchange);
        }
        // 当前AuthConfig
        final AuthConfig authConfig = serversConfig.getAuthConfig(route.getId());
        if (authConfig == null) {
            return chain.filter(exchange);
        }
        return chain.filter(exchange).then(Mono.create(monoSink -> {
            ServerHttpResponse response = exchange.getResponse();
            if (response.getStatusCode() != null && response.getStatusCode().is3xxRedirection()) {
                List<String> locations = response.getHeaders().get(HttpHeaders.LOCATION);
                URI locationUrl = null;
                if (locations != null && !locations.isEmpty()) {
                    for (String url : locations) {
                        if (StringUtils.isNotBlank(url)) {
                            locationUrl = UrlPathUtils.parseUri(url);
                            if (locationUrl != null) {
                                break;
                            }
                        }
                    }
                }
                URI currentUri = exchange.getRequest().getURI();
                if (locationUrl != null) {
                    StringBuilder sb = new StringBuilder(currentUri.getScheme() + "://" + currentUri.getHost());
                    if (currentUri.getPort() > 0 && currentUri.getPort() != 80) {
                        sb.append(":").append(currentUri.getPort());
                    }
                    sb.append(locationUrl.getPath());
                    if (locationUrl.getRawQuery() != null) {
                        sb.append("?").append(locationUrl.getRawQuery());
                    }
                    if (locationUrl.getRawFragment() != null) {
                        sb.append("#").append(locationUrl.getRawFragment());
                    }
                    log.info("Redirect URL替换: {} -> {}", locationUrl.toString(), sb.toString());
                    response.getHeaders().set(HttpHeaders.LOCATION, sb.toString());
                }
            }
            monoSink.success();
        }));
    }

    @Override
    public int getOrder() {
        return Order;
    }
}
